package com.vf.activity.controller;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.dtflys.forest.annotation.Post;
import com.github.pagehelper.PageInfo;
import com.vf.activity.domain.DTO.*;
import com.vf.activity.domain.VO.ActivityVO;
import com.vf.activity.domain.VO.AddActivityVO;
import com.vf.common.annotation.Anonymous;
import com.vf.common.utils.LocalUtil;
import com.vf.common.utils.SplitLocationUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.format.annotation.DateTimeFormat;
import com.vf.common.annotation.Log;
import com.vf.common.core.controller.BaseController;
import com.vf.common.core.domain.AjaxResult;
import com.vf.common.enums.BusinessType;
import com.vf.activity.domain.Activities;
import com.vf.activity.service.IActivitiesService;
import com.vf.common.utils.poi.ExcelUtil;
import com.vf.common.core.page.TableDataInfo;

/**
 * 活动Controller
 * 
 * @author LBS
 * @date 2025-06-04
 */
@RestController
@RequestMapping("/activity/activities")
@Api(tags="活动")
public class ActivitiesController extends BaseController
{
    @Autowired
    private IActivitiesService activitiesService;

    /**
     * 查询活动列表
     */
//    @PreAuthorize("@ss.hasPermi('activity:activities:list')")
    @GetMapping("/list")
    @Anonymous
    @ApiOperation(value = "查询活动列表")
    public TableDataInfo list(Activities activities)
    {
        startPage();
        List<Activities> list = activitiesService.selectActivitiesList(activities);
        return getDataTable(list);
    }

    /**
     * 导出活动列表
     */
    @PreAuthorize("@ss.hasPermi('activity:activities:export')")
    @Log(title = "活动", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Activities activities)
    {
        List<Activities> list = activitiesService.selectActivitiesList(activities);
        ExcelUtil<Activities> util = new ExcelUtil<Activities>(Activities.class);
        util.exportExcel(response, list, "活动数据");
    }

    /**
     * 获取活动详细信息
     */
    @PreAuthorize("@ss.hasPermi('activity:activities:query')")
    @GetMapping(value = "/{activityId}")
    public AjaxResult getInfo(@PathVariable("activityId") Long activityId)
    {
        return success(activitiesService.selectActivitiesByActivityId(activityId));
    }

    /**
     * 新增活动
     */
    @PreAuthorize("@ss.hasPermi('activity:activities:add')")
    @Log(title = "活动", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Activities activities)
    {
        return toAjax(activitiesService.insertActivities(activities));
    }

    /**
     * 修改活动
     */
    @PreAuthorize("@ss.hasPermi('activity:activities:edit')")
    @Log(title = "活动", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Activities activities)
    {
        return toAjax(activitiesService.updateActivities(activities));
    }

    /**
     * 删除活动
     */
    @PreAuthorize("@ss.hasPermi('activity:activities:remove')")
    @Log(title = "活动", businessType = BusinessType.DELETE)
	@DeleteMapping("/{activityIds}")
    public AjaxResult remove(@PathVariable Long[] activityIds)
    {
        return toAjax(activitiesService.deleteActivitiesByActivityIds(activityIds));
    }

    /**
     * 通过活动名称查询活动信息
     */
    @GetMapping("/getActivityByName")
    @Anonymous
    @ApiOperation("通过活动名称查询活动信息")
    public AjaxResult getActivityByName(ActDTO activityName)
    {
        List<ActivitiesDTO> activitiesList = activitiesService.selectActivitiesListByName(activityName);
        return  success(activitiesList);
    }

    @GetMapping(value = "/getInfo")
    @ApiOperation("通过活动iD获取活动信息")
    @Anonymous
    public AjaxResult getInfoById(Long activityId)
    {
        return success(activitiesService.getInfoById(activityId));
    }



    /**
     * 查询活动列表
     */
    @GetMapping("/listAll")
    @Anonymous
    @ApiOperation(value = "查询所有活动列表")
    public TableDataInfo listAll(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String location,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize
    )
    {
        Date date = null;
        if (!"全部时间".equals(startTime) && startTime != null && !startTime.isEmpty() ){
            String dateString = startTime;
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate = LocalDate.parse(dateString, formatter);
            date = Date.from(localDate.atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toInstant());
        }
        SplitLocationUtil.AddressInfo addressInfo = SplitLocationUtil.parseAddress(location);
        ActDTO activities =new ActDTO(keyword, type, addressInfo.getProvince(), addressInfo.getCity(), addressInfo.getDistrict(), date, pageNum, pageSize);
        return activitiesService.selectActivitiesAllList(activities);
    }

    /**
     * 通过分组查看查询活动列表
     */
    @GetMapping("/listByGroup")
    @Anonymous
    @ApiOperation(value = "通过分组查看查询活动列表")
    public TableDataInfo listByGroup(@RequestBody Long[] userIds){
        startPage();
        List<ActivitiesDTO> list = activitiesService.listByGroup(userIds);
        return getDataTable(list);
    }

    // 发布活动
    @PostMapping("/addActivity")
    @Anonymous
    @ApiOperation(value = "发布活动")
    public AjaxResult addActivity(@RequestBody ActivityVO activityVO){
        // 调用服务层方法添加活动，并转换结果为AjaxResult对象返回
        return toAjax(activitiesService.addActivity(activityVO));
    }

    // 加入活动
    @PostMapping("/joinActivity")
    @Anonymous
    @ApiOperation(value = "加入活动")
    public AjaxResult joinActivity(@RequestBody AddActivityVO addActivityVO){
        // 调用服务层方法加入活动，并转换结果为AjaxResult对象返回
        int i = activitiesService.joinActivity(addActivityVO);
        if (i == 1){
            return success("等待审核");
        }else if (i == -1){
            return success("活动已申请，等待审核");
        }
        return success("人数已满");
    }


//    @GetMapping("/list")
//    @Anonymous
//    @ApiOperation(value = "根据查询所有活动列表")
//    public TableDataInfo listAllBy(ActDTO activities)
//    {
//        List<Activities> list = activitiesService.selectActivitiesListAll(activities);
//        return getDataTable(list);
//    }

    @GetMapping("/joinActivityById")
    @Anonymous
    @ApiOperation(value = "用户参加的活动")
    public AjaxResult joinActivityById(@RequestParam Long userId,@RequestParam String status){
        // 调用服务层方法加入活动，并转换结果为AjaxResult对象返回
        List<ActivitiesDTO> list= activitiesService.joinActivityById(userId, status);
        return success(list);
    }


    @PostMapping("/publishActivity")
    @Anonymous
    @ApiOperation(value = "发布活动2.0")
    public AjaxResult publishActiity(@RequestBody Activities2DTO activities2DTO){
        // 调用服务层方法加入活动，并转换结果为AjaxResult对象返回
        System.out.println(activities2DTO);
        return success( activitiesService.publishActivity(activities2DTO));
    }

    @GetMapping("/getActiveOpen")
    @Anonymous
    @ApiOperation("获取显示内容")
    public AjaxResult getActiveOpen()
    {
        return success(activitiesService.getActiveOpen());
    }

    @GetMapping("/getAllActivities")
    @Anonymous
    @ApiOperation("所有活动")
    public AjaxResult getAllActivities(
            @RequestParam(required = true) String province,
            @RequestParam(required = true) String city,
            @RequestParam(required = false) String district,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String search
    )
    {
        ActivityTypeDTO activityTypeDTO = new ActivityTypeDTO(province, city, district, category, search);
        List<ActivitiesDTO> list = activitiesService.getAllActivities(activityTypeDTO);
        return success(list);
    }


    @Anonymous
    @ApiOperation("获取经纬度，返回地址")
    @PostMapping("/getlocation")
    public AjaxResult getlocation(@RequestBody LocationDTO locationDTO){
        String s = LocalUtil.GetLocationByAddress(locationDTO.getLongitude(), locationDTO.getLatitude());
        //江西省抚州市黎川县新城大道 区分省市区
        SplitLocationUtil.AddressInfo addressInfo = SplitLocationUtil.parseAddress(s);
        return success(addressInfo);
    }
}

